//
//  MySettingViewController.m
//  eshow
//
//  Created by Hisoka on 15/11/16.
//  Copyright © 2015年 Hisoka. All rights reserved.
//

#import "MySettingViewController.h"
#import "MyTableViewCell.h"
#import "MySettingTableViewCell.h"
#import "AboutUsViewController.h"

static NSString * const MY_CELL = @"myCell";
static NSString * const MY_SETTING_CELL = @"mySettingCell";

@interface MySettingViewController ()<UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>

@property (nonatomic, strong) UITableView *settingTV;
@property (nonatomic, strong) NSArray *iconArr;
@property (nonatomic, strong) NSArray *titleArr;

@end

@implementation MySettingViewController

- (void) viewWillAppear:(BOOL)animated {
    [self getAppSettingList];
}

- (void) viewDidDisappear:(BOOL)animated {
    [MobClick event:@"Click_Setting_backBTN"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self customizeBackItem];
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setStyle];
}

- (void) setStyle {
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    self.navigationItem.title = @"设置";
    
    self.view.backgroundColor = GRAY_COLOR;
    
    self.settingTV = [UITableView newAutoLayoutView];
    [self.view addSubview:_settingTV];
    
    [_settingTV autoPinToTopLayoutGuideOfViewController:self withInset:0];
    [_settingTV autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.view];
    [_settingTV autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.view];
    [_settingTV autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self.view];
    
    _settingTV.delegate = self;
    _settingTV.dataSource = self;
    _settingTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _settingTV.backgroundColor = GRAY_COLOR;
    _settingTV.hidden = YES;
    
    [_settingTV registerClass:[MyTableViewCell class] forCellReuseIdentifier:MY_CELL];
    [_settingTV registerClass:[MySettingTableViewCell class] forCellReuseIdentifier:MY_SETTING_CELL];
    
//    self.iconArr = @[@[@"", @"aboutAppICON", @"clearCacheICON"],
////                     @[@"checkUpdateICON"],
//                     @[]];
//    
//    self.titleArr = @[@[@"", @"关于应用", @"清除缓存"],
////                      @[@"检查更新"],
//                      @[]];
    
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return [self.iconArr[section] count];
    }else{
        return 1;
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
//    tableView.backgroundColor = GRAY_COLOR;
    
    if (section == 0) {
        return 0;
    }else if(section == 1){
        return 40;
    }else{
        return 10;
    }
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    headerV.backgroundColor = GRAY_COLOR;
    
    return headerV;

}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 140;
    }else{
        return 50;
    }
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        MySettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MY_SETTING_CELL forIndexPath:indexPath];

        cell.bgImg.hidden = NO;
        cell.btnImg.hidden = YES;
        cell.backgroundColor = GRAY_COLOR;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }else if(indexPath.section == 1 && indexPath.row == 0) {
        MySettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MY_SETTING_CELL forIndexPath:indexPath];
        
        cell.bgImg.hidden = YES;
        cell.btnImg.hidden = NO;
        cell.btnImg.image = [UIImage imageNamed:@"logoutBTN"];
        cell.backgroundColor = GRAY_COLOR;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }else{
        MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MY_CELL forIndexPath:indexPath];
        
        cell.iconImg.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", _iconArr[indexPath.section][indexPath.row]]];
        cell.titleLB.text = [NSString stringWithFormat:@"%@", _titleArr[indexPath.section][indexPath.row]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        return cell;
    }
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        

        if (indexPath.row == 1) {
            
            if ([_iconArr[indexPath.section][indexPath.row] isEqualToString:@"clearCacheICON"]) {
                [MobClick event:@"Click_Setting_cleanCache"];
                // 清除缓存
                [SVProgressHUD show];
                [self performSelector:@selector(clearCache) withObject:nil afterDelay:2.0f];
            }else{
                [MobClick event:@"Click_Setting_aboutApp"];
                
                AboutUsViewController *aboutVC = [[AboutUsViewController alloc] init];
                [self.navigationController pushViewController:aboutVC animated:YES];
            }

        }else if (indexPath.row == 2){
            [MobClick event:@"Click_Setting_cleanCache"];
            // 清除缓存
            [SVProgressHUD show];
            [self performSelector:@selector(clearCache) withObject:nil afterDelay:2.0f];
        }
        
    }else if (indexPath.section == 1){
        [MobClick event:@"Click_Setting_Logout"];
        
        [self logout];
//        [MobClick event:@"Click_Setting_checkNew"];
//
//        [self checkVersion];
    }else{

    }
}

#pragma mark - 注销登陆
- (void) logout {
    NSString *devModel = [[TMCache sharedCache] objectForKey:@"deviceModel"];
    
    [[TMCache sharedCache] removeAllObjects];
    
    [[TMCache sharedCache] setObject:devModel forKey:@"deviceModel"];
    
    [SVProgressHUD showInfoWithStatus:@"注销成功"];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 清除缓存
- (void) clearCache {
    
    float tmpSize = [[SDImageCache sharedImageCache] getSize] / 1024 / 1024;
    
    [[SDImageCache sharedImageCache] clearDisk];
    
    NSString *clearCacheName = tmpSize >= 1 ? [NSString stringWithFormat:@"清理缓存(%.2fM)", tmpSize] : [NSString stringWithFormat:@"清理缓存(%.2fk)", tmpSize * 1024];
    
    [SVProgressHUD showInfoWithStatus:clearCacheName maskType:SVProgressHUDMaskTypeBlack];
    
//    [SVProgressHUD showInfoWithStatus:@"成功清除缓存" maskType:SVProgressHUDMaskTypeBlack];
}

#pragma mark - 检测更新
- (void) checkVersion {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:APP_VER forKey:@"ver"];
    
    [[HttpManager instance] requestWithMethod:@"Util/checkVer"
                                   parameters:parameters
                                      success:^(NSDictionary *result) {
                                          NSString *hasNew = [[result objectForKey:@"data"] objectForKey:@"has_new"];
                                          NSString *alertInfo = [[result objectForKey:@"data"] objectForKey:@"info"];
                                          
                                          if ([hasNew isEqualToString:@"1"]) {
                                              if (IS_OS_9_OR_LATER) {
                                                  UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"检测更新"
                                                                                                                 message:alertInfo
                                                                                                          preferredStyle:UIAlertControllerStyleAlert];
                                                  [alert addAction:[UIAlertAction actionWithTitle:@"暂不更新"
                                                                                           style:UIAlertActionStyleCancel
                                                                                         handler:^(UIAlertAction * _Nonnull action) {
                                                                                             NSLog(@"update later");
                                                                                         }]];
                                                  [alert addAction:[UIAlertAction actionWithTitle:@"马上更新"
                                                                                            style:UIAlertActionStyleDefault
                                                                                          handler:^(UIAlertAction * _Nonnull action) {
                                                                                              NSLog(@"update");
                                                                                          }]];
                                                  
                                                  [self presentViewController:alert animated:YES completion:nil];
                                              }else{
                                                  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"检测更新"
                                                                                                  message:alertInfo
                                                                                                 delegate:self
                                                                                        cancelButtonTitle:@"暂不更新"
                                                                                        otherButtonTitles:@"马上更新", nil];
                                                  [alert show];
                                              }

                                          }else{
                                              [SVProgressHUD showInfoWithStatus:alertInfo];
                                          }
                                      }
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                          [SVProgressHUD showInfoWithStatus:[error localizedDescription] maskType:SVProgressHUDMaskTypeBlack];
                                      }];
}

- (void) alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        
    }
}

#pragma mark - 检测设置列表
- (void) getAppSettingList {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[[TMCache sharedCache] objectForKey:@"SSID"] forKey:@"ssid"];
    
    [SVProgressHUD show];
    [[HttpManager instance] requestWithMethod:@"Util/checkApp"
                                   parameters:parameters
                                      success:^(NSDictionary *result) {
                                          
                                          NSDictionary *tmp = [result objectForKey:@"data"];
                                          
                                          self.titleArr = [tmp objectForKey:@"name"];
                                          self.iconArr = [tmp objectForKey:@"icon"];
                                          [_settingTV reloadData];
                                          _settingTV.hidden = NO;
                                          
                                          [SVProgressHUD dismiss];
                                      }
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                          [SVProgressHUD showInfoWithStatus:[error localizedDescription] maskType:SVProgressHUDMaskTypeBlack];
                                      }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
